<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/26
 * Time: 17:24
 */

namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use common\models\datas\Category;
use common\models\datas\Student;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\OrdersItems;
use yii\data\ArrayDataProvider;
use zhtfrontend\modules\sitepadapi\components\rest\ActivebackController;
use zhtfrontend\models\datas\Order;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\web\Response;

class OrdersalesController extends ActivebackController
{
    public $modelClass = 'zhtfrontend\models\datas\OrderSales';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionIndex()
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['type' => 0]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionExpand($customer_id)
    {
        $time = [];
        $modelClass = $this->modelClass;
        $order = Order::find()->select('id')->where(['customer_id' => $customer_id, 'is_appointment' => 1])->orderBy('id ASC')->asArray()->column();
        $num = $modelClass::find()->where(['in', 'order_id', $order])->count();
        $order_sales = $modelClass::find()->where(['in', 'order_id', $order])->andWhere(['type' => 0])->asArray()->all();
        foreach ($order_sales as $k => $v) {
            $time[] = $v['class_day'] . $v['class_time'];
        }
        $data['items'] = [
            'num' => $num,
            'time' => $time,
        ];
        return $data;
    }

    //教师端我的预约
    public function actionCate($teacher_id)
    {
        $categoryId = (new Query())->select('o.category_id')->from('{{%admin}} a')
            ->leftJoin('{{%order_sales}} o', 'a.teacher_id=o.teacher_id')
            ->where(['a.id' => $teacher_id])
            ->groupBy('o.category_id')
            ->column(Fun::getSiteDb());
        $category = Category::find()->where(['in', 'id', $categoryId]);
        $dataProvider = new ActiveDataProvider([
            'query' => $category
        ]);
       /* return $dataProvider->getModels();
        var_dump($dataProvider->getModels());exit();*/
        return new ActiveDataProvider([
            'query' => $category
        ]);
    }

    public function actionFindbyparams($teacher_id, $category_id = '')
    {
        $data = [];
        //$this->getSiteDb(Fun::getSiteId());
        $teacher = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $teacher_id])->one(Fun::getSiteDb());
        $orderSalesQuery = (new Query())->select('*')->from('{{%order_sales}}')
            ->where(['site_id' => Fun::getSiteId(), 'type' => 0, 'teacher_id' => $teacher['teacher_id']]);
        if (!empty($category_id)) {
            $orderSalesQuery = $orderSalesQuery->andWhere(['category_id' => $category_id])->groupBy('category_id');
        }
        $orderSales = $orderSalesQuery->addGroupBy(['course_id', 'start_time', 'end_time'])->all(Fun::getSiteDb());
        foreach ($orderSales as $k => $v) {
            $data[] = [
                'category_id' => $v['category_id'],
                'category_name' => $v['category_name'],
                'course_data' => [
                    'course_name' => $v['title'],
                    'course_time' => $this->getTime($v['start_time'], $v['end_time']),
                    'current_num' => $this->getNumStatus($v['course_id'], $v['class_day'], $v['max_number'], $v['start_time'], $v['end_time'])['num'],
                    'course_status' => $this->getNumStatus($v['course_id'], $v['class_day'], $v['max_number'], $v['start_time'], $v['end_time'])['status'],
                    'student_list' => $this->getStudentList($v['sales_id'])
                ]
            ];
        };
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20,
            ],
            'sort' => [
                'attributes' => ['id'],
            ],
        ]);
    }

    //班主任我得预约
    public function actionCategory($teacher_id)
    {
        $cateId = [];
        $classManage = ClassManage::find()->select('*')
            ->where(['headmaster' => $teacher_id])->asArray()->all();
        foreach ($classManage as $k => $v) {
            switch ($v['is_old']) {
                case 0://关联商品id
                    $goods = Goods::find()->select('*')->where(['id' => $v['associate_id']])->asArray()->all();
                    foreach ($goods as $k => $v) {
                        $cateId[] = $v['cat_id'];
                    }
                    break;
                case 1;//关联排课id
                    $arrangement = Arrangement::find()->select('*')->where(['id' => $v['associate_id']])->asArray()->one();
                    $goods = Course::find()->select('*')->where(['id' => $arrangement['course_id']])->asArray()->all();
                    foreach ($goods as $k => $v) {
                        $cateId[] = $v['category_id'];
                    }
                    break;
            }
        }
        $categoryData = (new Query())->select(['c.id as category_id', 'c.name as category_name'])
            ->from('{{%cate}} c')
            ->where(['in', 'c.id', $cateId])
            ->andWhere(['type_id' => 1])
            ->groupBy('c.id');
        return new ActiveDataProvider([
            'query' => $categoryData
        ]);
    }

    public function actionFindbyparam($headmaster_id, $category_id = '')
    {
        $data = [];
        $arrangement = ClassManage::find()->where(['headmaster' => $headmaster_id])->asArray()->all();
        foreach ($arrangement as $key => $val) {
            switch ($val['is_old']) {
                case 0://关联商品id
                    $query = Goods::find()->select('*')->where(['id' => $val['associate_id']]);
                    if (!empty($category_id)) {
                        $query = $query->andWhere(['cat_id' => $category_id]);
                    }
                    $goods = $query->asArray()->one();
                    $data[] = [
                        'category_id' => $goods['cat_id'],
                        'category_name' => 'test',
                        'course_data' => [
                            'course_name' => $goods['name'],
                            'course_time' => '9:00-11:00',
                            'current_num' => '000',
                            'course_status' => '0',
                            'student_list' => $this->getStudentList($goods['id'])
                        ]
                    ];
                    break;
                case 1;//关联排课id
                    $arrangement = Arrangement::find()->select('course_id')->where(['id' => $val['associate_id']])->asArray()->one();
                    $goodsAttr = GoodsAttr::find()->select('goods_id')->where(['attribute_id' => $arrangement['course_id'], 'obj_type' => 'course'])->column();
                    $query = Goods::find()->where(['in', 'id', $goodsAttr]);
                    if (!empty($category_id)) {
                        $query = $query->andWhere(['cat_id' => $category_id]);
                    }
                    $goods = $query->asArray()->all();
                    foreach ($goods as $k => $v) {
                        $data[] = [
                            'category_id' => $v['cat_id'],
                            'category_name' => 'test',
                            'course_data' => [
                                'course_name' => $v['title'],
                                'course_time' => '9:00-11:00',
                                'current_num' => '000',
                                'course_status' => '0',
                                'student_list' => $this->getStudentList($v['id'])
                            ]
                        ];
                    };
                    break;
            }
        }
        $dataProvider= new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20,
            ],
            'sort' => [
                'attributes' => ['id'],
            ],
        ]);
        return $dataProvider->getModels();
    }

    protected function getCourseName($course_id)
    {
        $courseData = (new Query())->select('*')->from('{{%course}}')->where([
            'id' => $course_id, 'site_id' => Fun::getSiteId()
        ])->one();
        return $courseData['name'];
    }

    protected function getTime($start_time, $end_time)
    {
        $startTime = (strlen($start_time) == 3) ? substr($start_time, 0, 1) . ':' . substr($start_time, 1) : substr($start_time, 0, 2) . ':' . substr($start_time, 2);
        $endTime = (strlen($end_time) == 3) ? substr($end_time, 0, 1) . ':' . substr($end_time, 1) : substr($end_time, 0, 2) . ':' . substr($end_time, 2);
        $currentTime = $startTime . '-' . $endTime;
        return $currentTime;
    }

    protected function getNumStatus($course_id, $class_day, $max_number, $start_time, $end_time)
    {
        /*$this->getSiteDb(Fun::getSiteId());
        $currentNum = (new Query())->select('*')->from('{{%order_sales}}')->where([
            'course_id' => $course_id, 'class_day' => $class_day, 'start_time' => $start_time, 'end_time' => $end_time, 'site_id' => Fun::getSiteId()
        ])->count();
        $num = $currentNum . '/' . $max_number;
        $status = ($currentNum >= $max_number) ? '人数已满' : '人数未满';*/
        return [
            /*'num' => $num,
            'status' => $status*/
            'num' => 10,
            'status' => '人数已满'
        ];
    }

    protected function getStudentList($sales_id)
    {
        $data = [];
        $ordersItems = OrdersItems::find()->select('student_id')->where(['goods_id' => $sales_id])->asArray()->column();
        $student = Student::find()->where(['in', 'id', [365,367,368,369]])->asArray()->all();
        foreach ($student as $k => $v) {
            $data[] = [
                'student_img' => empty($v['img']) ? 'http://img.doumiaoduo.com/uploadfiles/system/7/images/20150930/1443585707110653.png' : $v['img'],
                'student_name' => empty($v['name']) ? 'test' : $v['name'],
                'order_time' => \Yii::$app->formatter->asDatetime(time(), 'yyyy-MM-dd h:i:s'),
                //'current_status' => $this->Deposit($v['id'])
                'current_status' => '已预约'
            ];
        }

        return $data;
    }

    protected function Deposit($order_sales_id)
    {
        $info = '';
        $data = (new Query())->select('*')->from('{{%ordercourse_history}}')->where(['order_sales_id' => $order_sales_id])->one();
        switch ($data['is_deposit']) {
            case 0:
                $info = '已预约';
                break;
            case 1:
                $info = '已办理入学';
                break;
        }
        return $info;
    }

    protected function getSiteDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        \Yii::$app->set('db', $site_cache[$site]['db']);
    }

}